package com.car.rental.vehicle.listener;

import com.car.rental.vehicle.service.VehicleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;

import java.io.IOException;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class VehicleStatusListener {

    private final VehicleService vehicleService;

    // 监听车辆状态变更队列的消息
    // 处理三种状态变更场景：
    // 1. 用户还车后变更为维修中(0)
    // 2. 商家确认后变更为可租用(1)
    // 3. 用户租车支付成功后变更为已租出(2)
    @RabbitListener(queues = "vehicle.status.queue")
    public void handleVehicleStatusChange(Map<String, Object> message, Channel channel, Message originalMessage) {
        try {
            // 从消息中解析车辆ID和目标状态
            Long vehicleId = (Long) message.get("vehicleId");
            Integer status = (Integer) message.get("status");
            
            log.info("收到车辆状态变更消息，车辆ID：{}，新状态：{}", vehicleId, status);
            
            // 调用服务层更新车辆状态
            vehicleService.updateStatus(vehicleId, status);
            
            // 手动确认消息已处理成功
            channel.basicAck(originalMessage.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("处理车辆状态变更消息失败", e);
            try {
                // 处理失败时，拒绝消息并重新入队，等待重试
                channel.basicNack(originalMessage.getMessageProperties().getDeliveryTag(), false, true);
            } catch (IOException ex) {
                log.error("消息确认失败", ex);
            }
        }
    }
} 